<template>
  <div :class="$style.add">
    <!-- <Button type="primary" :disabled="isEdit&&Object.keys(tmpData).length<=0" @click="clickHandle">{{ text }}</Button> -->
    <Button type="primary" @click="clickHandle">{{ text }}</Button>
    <el-dialog
      :visible.sync="visible"
      :title="title"
      :close-on-click-modal="false"
      @opened="initFromData"
      @close="resetForm"
    >
      <FormContainer :column="1">
        <el-form
          ref="form"
          :model="formData"
          :rules="formRules"
          label-width="90px"
        >
          <el-form-item prop="name" label="模板名称">
            <el-input v-model="formData.name" placeholder="请输入模板名称" clearable />
          </el-form-item>
          <el-form-item prop="content" label="模板内容">
            <el-input v-model="formData.content" placeholder="请输入模板内容" type="textarea" :autosize="{minRows:3}" />
            <span class="input-tip">剩余{{ surplus }}字</span>
          </el-form-item>
          <el-form-item prop="enabled" label="模板状态">
            <el-select v-model="formData.enabled" clearable filterable>
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="enableEditing" label="是否允许编辑">
            <el-select v-model="formData.enableEditing" clearable filterable>
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="group" label="使用业务组">
            <el-select v-model="formData.group" multiple clearable filterable>
              <el-option v-for="(bg,i) in groupList" :key="i" :label="bg.groupName" :value="bg.groupNo" />
            </el-select>
          </el-form-item>
          <el-form-item prop="masterId" label="模板主人">
            <el-select v-model="formData.masterId" remote :remote-method="getStaffList" clearable filterable>
              <el-option v-for="(s,i) in statffList" :key="i" :label="`${s.staffName}(${s.accountNo})`" :value="s.accountNo" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <Button type="primary" :loading="loading" @click="submitHandle">{{ isEdit?'保存':'创建' }}</Button>
            <Button type="primary" @click="initFromData">重置</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import Button from '@/components/Button'
import FormContainer from '@/components/FormContainer'
import { filtersRaw, pageRequsetBody, deepCopy, numToString } from '@/utils'
// import { getBusinessAll } from '@/api/business'
import { getStaffInfo } from '@/api/staffInfo'
import { postMessageTemplate, putMessageTemplate } from '@/api/smsOrEmailTemp'
import { mapGetters } from 'vuex'
export default {
  name: 'Add',
  components: {
    Button,
    FormContainer
  },
  props: {
    text: {
      type: [Number, String],
      default: ''
    },
    title: {
      type: [Number, String],
      default: ''
    },
    tmpData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatorGroup = (r, v, c) => {
      if (v.length <= 0) {
        c(new Error('请选择业务组！'))
      } else {
        c()
      }
    }
    // 验证短信内容
    const validatorContent = (r, v, c) => {
      if (v.length > this.maxNum) {
        c(new Error(`最多输入${this.maxNum}个字符`))
      } else {
        c()
      }
    }
    return {
      visible: false,
      maxNum: 150,
      // groupList: [], // 组数据
      statffList: [], // 员工数据
      formData: {
        name: '',
        content: '',
        enabled: '', // 模板状态1-启用0-停用
        enableEditing: '', // 是否允许编辑1-允许0-不允许
        group: [], // 使用组织编码
        masterId: '',
        type: 1
      },
      formRules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'change' }],
        content: [{ required: true, message: '请输入模板内容', trigger: 'change' },
          { validator: validatorContent, trigger: 'change' }],
        enabled: [{ required: true, message: '请选择模板状态', trigger: 'change' }],
        enableEditing: [{ required: true, message: '请选择是否可编辑', trigger: 'change' }],
        group: [{ required: true, message: '请选择业务组', trigger: 'change' },
          { required: true, validator: validatorGroup, trigger: 'change' }],
        masterId: [{ required: true, message: '请选择模板主人', trigger: 'change' }]
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters(['groupList']),
    surplus() {
      const t = this.maxNum - this.formData.content.length
      return t >= 0 ? t : 0
    }
  },
  created() {
    // this.getGroup()
    this.getStaffList()
  },
  methods: {
    clickHandle() {
      if (this.isEdit && Object.keys(this.tmpData).length <= 0) {
        this.$message.error('请选择要编辑的行！')
        return
      }
      if (this.isEdit && !this.operatePer(this.tmpData)) {
        this.$message.error('您不能操作该条数据！')
        return
      }
      this.visible = true
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    submitHandle() {
      this.loading = true
      this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        const group = []
        for (const o of data.group) {
          for (const g of this.groupList) {
            if (g.groupNo === o) {
              group.push({
                groupNo: o,
                groupName: g.groupName
              })
              break
            }
          }
        }
        data.group = group
        for (const s of this.statffList) {
          if (s.accountNo === data.masterId) {
            data.masterName = s.staffName
            break
          }
        }
        // 成功的
        let ajax = postMessageTemplate
        if (this.isEdit) {
          ajax = putMessageTemplate
          data.id = this.tmpData.id
        }
        return ajax(data).then(res => {
          this.visible = false
          this.$emit('on-refresh')
          let msg = '添加成功！'
          if (this.isEdit) {
            msg = '保存成功！'
          }
          this.$message.success(msg)
          return res
        })
      }).finally(() => {
        this.loading = false
      })
    },
    // 编辑，初始化数据
    initFromData() {
      this.resetForm()
      if (this.isEdit) {
        for (const key of Object.keys(this.formData)) {
          let v = this.tmpData[key]
          if (key === 'group') {
            v = v.map(e => numToString(e.groupNo))
          } else if (key === 'enableEditing') {
            v = parseInt(v)
          }
          this.$set(this.formData, key, v)
        }
      }
    },
    // // 获取业务组
    // getGroup() {
    //   getBusinessAll().then(res => {
    //     this.groupList = res.data
    //   })
    // },
    // 获取员工
    getStaffList(v) {
      const data = {
        pageFlag: true
        // filtersRaw: [
        // filtersRaw('staffName', v, 'like')
        // ]
      }
      if (/^[a-zA-Z]+$/.test(v)) {
        data.filtersRaw = [
          filtersRaw('accountNo', v, 'like')
        ]
      } else {
        data.filtersRaw = [
          filtersRaw('staffName', v, 'like')
        ]
      }
      getStaffInfo(pageRequsetBody(data)).then(res => {
        this.statffList = res.data.records
      })
    },
    // 操作权限判断
    operatePer(row) {
      let allow = false
      allow = this.$self(row.masterId)
      if (allow) return allow
      if (row.enableEditing === 1) {
        allow = row.group.some(e => this.$inGroup(e.groupNo))
      }
      return allow
    }
  }
}
</script>
<style lang="scss" module>
.add {
}
</style>
